package tests;

public class Keyongyu {
    static class Node {
        String data;
        Node next;

        public Node(String data) {
            this.data = data;
        }

        @Override
        public String toString() {
            if (next == null) {
                return "Node{" + data + "}";
            }
            return "Node{" + data + "}->" + next;
        }
    }

    public static Node delete(Node root, int index) {
        if (root == null)
            return null;
        if(index == 0){
            //如果是第一个，直接返回next
            return root.next;
        }
        int i = 1;
        Node cur = root.next;//从root的next开始遍历
        Node last = root;
        do {
            if (i == index) {
                last.next = cur.next;//当前节点的next赋值给上一个节点
                break;
            }
            i++;
            last = cur;
            cur = cur.next;
        } while (cur.next != null);
        return root;
    }

    public static void main(String[] args) {
        Node root = new Node("0");
        Node last = root;
        for (int i = 1; i < 19; i++) {
            Node node = new Node("" + i);
            last.next = node;
            last = node;
        }
        int deleteIndex = 14;//删除位置
        System.out.println("before:" + root);
        Node node = delete(root, deleteIndex);
        System.out.println("after:" + node);
    }
}